//
//  FKHttpTool.m
//  FKLibraryExample
//
//  Created by frank on 2018/8/13.
//  Copyright © 2018年 zmosa - frank. All rights reserved.
//

#import "FKHttpTool.h"
#import "FKAPIClient.h"
#import <MJExtension.h>
//#import "FKLocationTool.h"
// 引入 JPush 功能所需头文件
#import "JPUSHService.h"

@implementation FKHttpTool

+ (NSDictionary *)getHeaders:(NSString *)suffix
{
    if (!suffix) return nil;
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    if ([suffix isEqualToString:@"/api/user/login"]) {
        
    } else {
        NSString *token = [FKCacheTool getToken];
        if (token) {
            dict[@"token"] = token;
        }
    }
    return dict;
}

+ (void)postJsonWithSuffix:(NSString *)suffix param:(id)param success:(void (^)(FKBaseResult *))success failure:(void (^)(NSError *))failure
{
    NSString *requestUrl = [NSString stringWithFormat:@"%@%@", HostURL, suffix];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:requestUrl]];
    request.timeoutInterval = 30.0;
    request.cachePolicy = NSURLRequestReloadIgnoringCacheData;
    [request setHTTPMethod:@"POST"];
    [request setValue:[NSString stringWithFormat:@"application/json"] forHTTPHeaderField:@"Content-Type"];
    NSString *token = [FKCacheTool getToken];
    if (token) {
        [request setValue:token forHTTPHeaderField:@"token"];
    }
    NSString *paramStr = [param mj_JSONString];
    NSData *postData = [paramStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:postData];
    
    NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (error) {
                if (failure) failure(error);
            } else {
                if (success) {
                    NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                    NSDictionary *dict = [jsonStr mj_JSONObject];
                    FKBaseResult *result = [FKBaseResult mj_objectWithKeyValues:dict];
                    if (!result.isSuccess) {
                        if ([result.code isEqualToString:@"10"]) { // 被踢下线
                            [FKCacheTool logout];
                            [FKLoginTool showLoginBySwitchRootVC];
                        } else {
//                            [SVProgressHUD showInfoWithStatus:result.msg];
                        }
                    }
                    success(result);
                }
            }
        });
    }];
    [task resume];
}


+ (void)postWithSuffix:(NSString *)suffix param:(id)param success:(void (^)(FKBaseResult *))success failure:(void (^)(NSError *))failure
{
    FKAPIClient *manager = [FKAPIClient sharedClient];
    NSString *requestUrl = [NSString stringWithFormat:@"%@%@", HostURL, suffix];
    if ([param[@"hasHost"] boolValue]) { // 如果是全路径，就不用拼接主机地址了
        requestUrl = suffix;
    }
    __block BOOL hideError = [param[@"hideError"] boolValue];
    [manager POST:requestUrl parameters:param headers:[self getHeaders:suffix] progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            // 将请求回来的字典根据传入的resultClass转成对应的模型
            FKBaseResult *result = [FKBaseResult mj_objectWithKeyValues:responseObject];
            
            if (result.isSuccess) {
                
            } else {
                if (!hideError) {
//                    [SVProgressHUD showInfoWithStatus:result.msg];
                    FKLog(@"😄😄😄😄😄😄出错了: %@", result.msg)
                }
                if ([result.code isEqualToString:@"-1"]) {
                    [FKLoginTool showLoginByPresent];
                }
            }
            
            success(result);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (!hideError) {
            if ([error.localizedDescription containsString:@"401"]) {
                [FKLoginTool showLoginByPresent];
            } else if ([error.localizedDescription containsString:@"似乎已断开与互联网的连接"]) {
//                [SVProgressHUD showInfoWithStatus:@"网络异常!"];
            } else if ([error.localizedDescription containsString:@"404"]) {
//                [SVProgressHUD showInfoWithStatus:@"找不到对应的服务!"];
            } else {
//                [SVProgressHUD showInfoWithStatus:@"请求异常!"];
                FKLog(@"😄😄😄😄😄😄：请求异常")
            }
        }
//        NSLog(@"===(%@)===", error);
        if (failure) {
            failure(error);
        }
    }];
}


+ (void)getWithSuffix:(NSString *)suffix param:(id)param success:(void (^)(FKBaseResult *result))success failure:(void (^)(NSError *error))failure
{
    FKAPIClient *manager = [FKAPIClient sharedClient];
    
    NSString *requestUrl = [NSString stringWithFormat:@"%@%@", HostURL, suffix];
    if ([param[@"hasHost"] boolValue]) { // 如果是全路径，就不用拼接主机地址了
        requestUrl = suffix;
    }
    __block BOOL hideError = [param[@"hideError"] boolValue];
    [manager GET:requestUrl parameters:param headers:[self getHeaders:suffix] progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            // 将请求回来的字典根据传入的resultClass转成对应的模型
            FKBaseResult *result = [FKBaseResult mj_objectWithKeyValues:responseObject];
            success(result);
            
            
            if (!result.isSuccess) {
                if (!hideError) {
                    if ([result.code isEqualToString:@"200"]) {
                        // 当前版本与新版本相同，无需更新
                    } else {
//                        [SVProgressHUD showInfoWithStatus:result.msg];
                        FKLog(@"😄😄😄😄😄😄出错了: %@", result.msg)
                    }
                }
                if ([result.code isEqualToString:@"-1"]) {
                    [FKLoginTool showLoginByPresent];
                }
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        [SVProgressHUD showInfoWithStatus:@"请求异常!"];
        FKLog(@"😄😄😄😄😄😄：请求异常")
        if (failure) {
            failure(error);
        }
    }];
}

+ (void)uploadVideo:(NSURL *)localUrl progress:(void (^)(NSProgress *))progress success:(void (^)(FKBaseResult *))success failure:(void (^)(NSError *))failure
{
    FKAPIClient *manager = [FKAPIClient sharedClient];
    
    NSString *requestUrl = [NSString stringWithFormat:@"%@/upload/file/upload", HostURL];
    [manager POST:requestUrl parameters:nil headers:[self getHeaders:nil] constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSData *data = [NSData dataWithContentsOfURL:localUrl];
        [formData appendPartWithFileData:data name:@"files" fileName:@"iOS_video.mp4" mimeType:@"video/mp4"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        if (progress)  progress(uploadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (responseObject) {
            FKBaseResult *result = [FKBaseResult mj_objectWithKeyValues:responseObject];
            success(result);
            
            if (!result.isSuccess) {
                if ([result.code isEqualToString:@"10"]) { // 被踢下线
                    [FKCacheTool logout];
                    [FKLoginTool showLoginBySwitchRootVC];
                } else {
//                    [SVProgressHUD showInfoWithStatus:result.msg];
                }
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        [SVProgressHUD showInfoWithStatus:@"网络异常!"];
        if (failure) {
            failure(error);
        }
    }];
}

+ (void)uploadAudio:(NSURL *)localUrl progress:(void (^)(NSProgress *))progress success:(void (^)(FKBaseResult *))success failure:(void (^)(NSError *))failure
{
    FKAPIClient *manager = [FKAPIClient sharedClient];
    
    NSString *requestUrl = [NSString stringWithFormat:@"%@/upload/file/upload", HostURL];
    [manager POST:requestUrl parameters:nil headers:[self getHeaders:nil] constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSData *data = [NSData dataWithContentsOfURL:localUrl];
        [formData appendPartWithFileData:data name:@"files" fileName:@"iOS_audio.mp3" mimeType:@"audio/x-mpeg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        if (progress)  progress(uploadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (responseObject) {
            FKBaseResult *result = [FKBaseResult mj_objectWithKeyValues:responseObject];
            success(result);
            
            if (!result.isSuccess) {
                if ([result.code isEqualToString:@"10"]) { // 被踢下线
                    [FKCacheTool logout];
                    [FKLoginTool showLoginBySwitchRootVC];
                } else {
//                    [SVProgressHUD showInfoWithStatus:result.msg];
                }
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        [SVProgressHUD showInfoWithStatus:@"网络异常!"];
        if (failure) {
            failure(error);
        }
    }];
}

+ (void)uploadFile:(NSURL *)localUrl progress:(void (^)(NSProgress *))progress success:(void (^)(FKBaseResult *))success failure:(void (^)(NSError *))failure
{
    FKAPIClient *manager = [FKAPIClient sharedClient];
    
    NSString *requestUrl = [NSString stringWithFormat:@"%@/upload/file/upload", HostURL];
//    if ([FKCacheTool cookie]) {
//        [manager.requestSerializer setValue:[FKCacheTool cookie] forHTTPHeaderField:@"Cookie"];
//    }
    [manager POST:requestUrl parameters:nil headers:[self getHeaders:nil] constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSData *data = [NSData dataWithContentsOfURL:localUrl];
        NSString *fileName = localUrl.lastPathComponent;
        NSString *suffix = [fileName pathExtension];
        NSString *mimeType = @"image/png";
        if ([suffix isEqualToString:@"mp3"]) {
            mimeType = @"audio/x-mpeg";
        } else if ([suffix isEqualToString:@"pdf"] ||
                   [suffix isEqualToString:@"doc"] ||
                   [suffix isEqualToString:@"docx"] ||
                   [suffix isEqualToString:@"xls"] ||
                   [suffix isEqualToString:@"ppt"]) {
           mimeType = @"application/octet-stream";
        }
        [formData appendPartWithFileData:data name:@"files" fileName:fileName mimeType:mimeType];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        if (progress)  progress(uploadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (responseObject) {
            FKBaseResult *result = [FKBaseResult mj_objectWithKeyValues:responseObject];
            success(result);
            
            if (!result.isSuccess) {
                if ([result.code isEqualToString:@"10"]) { // 被踢下线
                    [FKCacheTool logout];
                    [FKLoginTool showLoginBySwitchRootVC];
                } else {
//                    [SVProgressHUD showInfoWithStatus:result.msg];
                }
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        [SVProgressHUD showInfoWithStatus:@"网络异常!"];
        if (failure) {
            failure(error);
        }
    }];
}


+ (void)uploadFile:(NSString *)suffix param:(id)param files:(NSDictionary *)files progress:(void (^)(NSProgress *))progress success:(void (^)(FKBaseResult *))success failure:(void (^)(NSError *))failure
{
    FKAPIClient *manager = [FKAPIClient sharedClient];
    
    NSString *requestUrl = [NSString stringWithFormat:@"%@%@", HostURL, suffix];
    [manager POST:requestUrl parameters:param headers:[self getHeaders:nil] constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        // 换一种遍历方式，block遍历可能会导致顺序错乱
        for (NSString *key in files) {
            NSData *data = UIImageJPEGRepresentation(files[key], 0.8);
            NSString *fileName = [NSString stringWithFormat:@"%@.png", key];
            [formData appendPartWithFileData:data name:@"files" fileName:fileName mimeType:@"image/png"];
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        if (progress) {
            progress(uploadProgress);
        }
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (responseObject) {
            FKBaseResult *result = [FKBaseResult mj_objectWithKeyValues:responseObject];
            success(result);
            
            if (!result.isSuccess) {
                if ([result.code isEqualToString:@"10"]) { // 被踢下线
                    [FKCacheTool logout];
                    [FKLoginTool showLoginBySwitchRootVC];
                } else {
//                    [SVProgressHUD showInfoWithStatus:result.msg];
                }
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        [SVProgressHUD showInfoWithStatus:@"网络异常!"];
        if (failure) {
            failure(error);
        }
    }];
}

+ (void)uploadImages:(NSArray *)images complete:(void(^)(NSString *, NSError *))complete
{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    for (NSInteger index = 0; index < images.count; index++) {
        NSString *key = fkFORMAT(@"image_%zd", index);
        param[key] = images[index];
    }
//    [SVProgressHUD showProgress:0.0f];
    [FKHttpTool uploadFile:@"/upload/file/upload" param:nil files:param progress:^(NSProgress *progress) {
//        [SVProgressHUD showProgress:progress.fractionCompleted];
    } success:^(FKBaseResult *result) {
//        [SVProgressHUD dismiss];
        if (result.isSuccess) {
            NSArray *list = result.data;
            NSMutableArray *paths = [NSMutableArray array];
            for (NSDictionary *dict in list) {
                [paths addObject:dict[@"filePath"]];
            }
            // 将图片路径以逗号拼接成一个字符串
            NSString *attachs = [paths componentsJoinedByString:@","];
            if (complete) complete(attachs, nil);
        } else {
            NSError *error1 = [[NSError alloc] init];
            complete(nil, error1);
        }
    } failure:^(NSError *error1) {
        complete(nil, error1);
    }];
}


+ (NSURLSessionDownloadTask *)downloadFile:(NSString *)suffix saveUrl:(NSURL *)saveUrl progress:(void (^)(NSProgress *))progress success:(void (^)(FKBaseResult *))success failure:(void (^)(NSError *))failure;
{
    FKAPIClient *manager = [FKAPIClient sharedClient];
    NSString *link = [NSString stringWithFormat:@"%@%@", HostURL, suffix];
    NSURL *url = [NSURL URLWithString:link];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        if (progress) progress(downloadProgress);
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        // 如果路径中的文件夹不存在，则创建文件夹
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSURL *folderUrl = [saveUrl URLByDeletingLastPathComponent];
        NSString *folderPath = folderUrl.path;
        if (![fileManager fileExistsAtPath:folderPath]) {
            NSError *error;
            [fileManager createDirectoryAtPath:folderPath withIntermediateDirectories:YES attributes:nil error:&error];
        }
        return saveUrl;
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        if (error) {
            if (failure) failure(error);
        } else {
            if (success) {
                NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                dict[@"filePath"] = filePath;
                dict[@"response"] = response;
                FKBaseResult *result = [[FKBaseResult alloc] init];
                result.code = @"0";
                result.msg = @"操作成功";
                result.success = true;
                result.data = dict;
                success(result);
            }
        }
    }];
    return task;
}

@end
